import type { ErrorMessageMode } from '/#/axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import useUserStore from '/@/store/modules/user';

export function checkStatus(
  status: number,
  msg: string,
  errorMessageMode: ErrorMessageMode = 'message',
): void {
  let errMessage = '';
  const route = useRoute();
  switch (status) {
    case 400:
      errMessage = `${msg}`;
      break;
    // 401: Not logged in
    // Jump to the login page if not logged in, and carry the path of the current page
    // Return to the current page after successful login. This step needs to be operated on the login page.
    case 401:
      errMessage = '';
      useUserStore()
        .logOut()
        .then(() => {
          if (route.meta.isAdmin) {
            location.href = '/login';
          } else {
            location.href = '/';
          }
        })
        .catch(() => {});

      break;
    case 403:
      errMessage = msg || '当前操作没有权限';
      break;
    // 404请求不存在
    case 404:
      errMessage = msg || '访问资源不存在';
      break;
    case 405:
      errMessage = msg || '禁用请求中指定的方法';
      break;
    case 408:
      errMessage = msg || '服务器等候请求时发生超时';
      break;
    case 500:
      errMessage = msg || '系统未知错误，请反馈给管理员';
      break;
    case 501:
      errMessage = msg || '尚未实施';
      break;
    case 502:
      errMessage = msg || '系统暂时不可用';
      break;
    case 503:
      errMessage = msg || '系统未知错误，请反馈给管理员';
      break;
    case 504:
      errMessage = msg || '系统停机维护，请反馈给管理员';
      break;
    case 505:
      errMessage = msg || '系统未知错误，请反馈给管理员';
      break;
    default:
  }

  if (errMessage) {
    if (errorMessageMode === 'modal') {
      ElMessageBox({ title: '系统提示', message: errMessage });
    } else if (errorMessageMode === 'message') {
      ElMessage({ message: errMessage, key: `global_error_message_status_${status}` });
    }
  }
}
